package com.aivin.lib_englishlearn;

import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import androidx.appcompat.widget.AppCompatTextView;


public class SelectWordTextView extends AppCompatTextView {
    private OnClickWordListener mOnClickWordListener;
    /**
     * 触发移动事件的最小距离
     */
    private int mTouchSlop;
    private float downX = 0;
    private float downY = 0;
    private int[] mTempPosition = new int[]{-1, -1};

    public SelectWordTextView(Context context) {
        super(context);
        init(context);
    }

    public SelectWordTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SelectWordTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context ) {
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }


    private long lastTime = 0 ;
    private void goTell( MotionEvent event ) {
        if (System.currentTimeMillis() - lastTime < 2000L) {
            String word = handleClickWord( getText().toString(), getOffsetForPosition(event.getX(), event.getY()));
            if (!TextUtils.isEmpty(word)) {
                mOnClickWordListener.onClickWord(word);
            }
        } else {
            lastTime = System.currentTimeMillis() ;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(mOnClickWordListener ==null){
            return true;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                downY = event.getY();
                break;

            case MotionEvent.ACTION_UP:
                if (Math.abs(event.getX() - downX) < mTouchSlop  && Math.abs(event.getY() - downY) < mTouchSlop) {
                    goTell(event);
                }
                performClick();
                break;

            default:
                break;
        }

        return true;
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }

    private int[] getWordPosition(String text, int offsetPosition) {
        if (offsetPosition >= text.length() || offsetPosition < 0
                || isNotLetter(text.charAt(offsetPosition))) {
            return null;
        }
        int endPositionOfWord = 0;
        int startPositionOfWord = 0;
        for (int i = offsetPosition; i < text.length(); i++) {
            if (i == text.length() - 1) {
                endPositionOfWord = i;
                break;
            }
            if (isEdge(text.charAt(i))) {
                endPositionOfWord = i;
                break;
            }

        }
        for (int i = offsetPosition; i >= 0; i--) {
            if (i == 0) {
                break;
            }
            if (isEdge(text.charAt(i))) {
                startPositionOfWord = i + 1;
                break;
            }

        }
        return new int[]{startPositionOfWord, endPositionOfWord};

    }

    private String handleClickWord(String text, int offsetPosition) {
        if (offsetPosition >= mTempPosition[0] && offsetPosition < mTempPosition[1]) {
            mTempPosition[0] = -1;
            mTempPosition[1] = -1;
            setText(text);
            return null;
        }

        int[] wordPosition = getWordPosition(text, offsetPosition);
        if (wordPosition == null) {
            return null;
        }
        int start = wordPosition[0];
        int end = wordPosition[1];

        mTempPosition[0] = start;
        mTempPosition[1] = end;

        SpannableString stringBuilder = new SpannableString(text);
        stringBuilder.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        setText(stringBuilder);
        return text.substring(start, end);
    }

    private boolean isEdge(char curr) {
        return curr == ' ' || curr == '\n'  || (isNotLetter(curr) && curr != '\'');
    }



    private boolean isNotLetter(char c) {
        return ! (  ( c >= 'a' && c <= 'z')   || (c >= 'A' && c <= 'Z') );
    }
    public void setOnClickWordListener(OnClickWordListener onClickWordListener) {
        mOnClickWordListener = onClickWordListener;
    }

    public interface OnClickWordListener {
        void onClickWord(String word);
    }

}
